/*
 * @Author: sunzhijun 
 * @Date: 2019-03-24 20:39:23 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-01 10:26:38
 */
/*
 * 传入this.props以便调用方法
 * @agFlag: 是否进入协议签订
 * @appCode: 本节点调用其他节点code
 * pkOrg: 组织节点
 */

import React, {Component} from 'react';
import {promptBox, base, cacheTools} from 'nc-lightapp-front';
import {hrAjax as ajax, saveValidate} from 'src/hrpub/common/utils/utils';
import {chectFormAction} from '../../../../../public/functions/checkFormAction';
import handdleCheckedData from '../../container/functions/checkDataPermissionAction';
import './index.less';

const { NCButton, NCSelect, NCCheckbox } = base;

const moduleId = "sign6011";
const domainName = "hrcm";

class FormCard extends Component{
    constructor(props){
        super(props);
        this.state = {
            agFlag: props.agFlag,
            dataCard_add : '', //formCard Id 初始为空
            pk_org: props.pkOrg,
            appCode: props.appCode || '',
            isSignEffect: false, //合同签订是否生效
            isProtocolEffect: false //协议签订是否生效
        }

        this.setFormCardId = this.setFormCardId.bind(this);
        this.setCheckbox = this.setCheckbox.bind(this);
        this.changeCheck = this.changeCheck.bind(this);


    }

    componentWillMount() {
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt})//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: moduleId, domainName: domainName, callback})
    }

    componentDidMount() {
        // cacheTools.set('isSignEffect', false);
        // cacheTools.set('isProtocolEffect', false);
    }
    //获取formCard模板及数据
    getFormCardData(selectData,agreementType){ 
        let pk_psnjob = [];
        selectData && selectData.map((v,i)=>{
            pk_psnjob.push(v.data.values.pk_psnjob.value);
        });
        let storage = window.localStorage.getItem('pageQueryParam');
        let sign_pk_psnjob = storage && storage.sign && storage.sign.pk_psndoc_subs;
        let psnJobs = pk_psnjob.length ? pk_psnjob : sign_pk_psnjob;
        let areaCode = 'dataCard';
        let areaCodeCard = '';
        let {pkOrg, appCode} = this.props;
        if(!!agreementType){
            areaCode = agreementType +'Card';
        }
        areaCodeCard = areaCode + '_add';
        this.props.use && this.props.use.form(areaCodeCard)  // 增加自定义协议得表单注册
        if(!!psnJobs){
            ajax ({
                url: '/nccloud/hrcm/common/DataInitAction.do',
                data: {
                    pk_psnjobs: psnJobs,
                    areaCode: areaCode,
                    appCode: appCode,
                    pk_org: pkOrg,
                    agreementType: agreementType || ''   //选中的协议类型
                },
                success: res => {
                    if(res.success){
                        let data = res.data;
                        let resultItems = data.resultData[areaCodeCard];
                        let template = {
                            [areaCodeCard]: data.template[areaCodeCard],
                            dataCard_value: resultItems,   //缓存本地待编辑数据备用
                            ...data.template
                        }
                        this.props.meta.addMeta(template,()=>{
                            this.setFormCardId(areaCodeCard,data.rollBackFlag,resultItems);
                            this.setState({
                                expandArr: data.template.formrelation && data.template.formrelation[areaCodeCard],
                                pageid: data.template.pageid
                            })
                        });
                    }
                }
            })
        }
    }

    //保存操作
    doneHandle(){
        this.doneDetailData();
    }

    //协议点击完成保存
    doneAgreementData(agreementType,listData,data,step){
        let pkPsndocSubs = cacheTools.get('pkPsndocSubs') || [];
        let {dataCard_add, expandArr} = this.state;
        let bodys_code = null;
        let billType = 'form';
        if(!this.props.form.isCheckNow(dataCard_add)){
            return false;
        }
        let selectFormData = this.props.form.getAllFormValue(dataCard_add).rows;
        let pk_psnjobArr = listData;
        // listData && listData.map((v,i)=>{
        //     pk_psnjobArr.push(v.data.values.pk_psnjob.value);
        // })
        
        let formData = {
            model: {
                rows: selectFormData
            }
        }
        if(!!expandArr && expandArr.length > 0){
            bodys_code = expandArr;
            billType = 'extcard';
        }
        saveValidate(this.props, dataCard_add, dataCard_add, bodys_code, billType).then(()=>{
            ajax({
                url: '/nccloud/hrcm/agreement/SignAddSaveAction.do',
                data: {
                    step: step || '0',
                    agreementType: agreementType,
                    pkPsnjobs: pk_psnjobArr,
                    formData: formData,
                    savedCtrtpks: data || [],
                    pkPsndocSubs: pkPsndocSubs
                },
                success: res => {
                    if(res.success){
                        let resData = res.data;
                        let resStep = resData.step;
                        let savedCtrtpks = resData.savedCtrtpks;
                        let isSignEffect = cacheTools.get('isSignEffect');
                        if(resStep == '1'){
                            let fn = {
                                sureFn: () => this.doneAgreementData(agreementType,listData,savedCtrtpks,resStep),
                                cancelFn : () =>  this.props.closeFormCardModal && this.props.closeFormCardModal({data: savedCtrtpks,type: '2',isSignEffect: isSignEffect}) //type 2 协议标示
                            }
                            this.promptBoxModal(resData.msg, fn);
                        }else if(resStep == '99'){ 
                            // let { isSignEffect,agFlag } = this.state;
                            // this.props.closeFormCardModal();
                            // cacheTools.set('isProtocolEffect', true);
                            // this.setState({
                            //     isProtocolEffect :true
                            // },()=>{
                                this.props.closeFormCardModal && this.props.closeFormCardModal({data:savedCtrtpks,flag: false,type: '2',isProtocolEffect: true,isSignEffect: isSignEffect});
                            // })
                        }
                    }
                }
            })
        })
    }
    
    //合同点击完成第一步保存
    doneDetailData(step){
        let {dataCard_add, pageid} = this.state;
        if(!this.props.form.isCheckNow(dataCard_add)){
            return false;
        }
        let selectFormData = this.props.form.getAllFormValue(dataCard_add).rows;
        let { pkOrg, appCode} = this.props;
        let formData = {
            model: {
                rows: selectFormData
            }
        } 
        saveValidate(this.props, pageid, dataCard_add, null, 'form').then(()=>{
            ajax({
                url: '/nccloud/hrcm/make/MakeAddSaveAction.do',
                data: {
                    step: step || '0',
                    appCode: appCode,
                    pk_org: pkOrg,
                    modename: 'hi_psndoc_ctrt',     //暂时写死
                    formData: formData          //第二步卡片数据，传整个form表单
                },
                success: res => {
                    if(res.success && res.data){
                        let data = res.data.savedData;
                        let step = res.data.step;
                        if(step === '1'){
                            let fn = {
                                sureFn: () => this.doneDetailData(step)
                            }
                            this.promptBoxModal(res.data.msg, fn);
                        }else if(step === '3'){
                            this.doneDetailDataAfter(data,step);
                        }else{
                            this.doneDetailData(step);
                        }
                    }
                }
            })
        })
    }

    //点击是否立即生效事件
    isTakeEffectEvent(savedData,step){
        !!savedData && handdleCheckedData(savedData, 'effect', 'contract', ()=>{
            this.doneDetailDataAfter(savedData,step);
        });
    }

    //合同点击完成第二步是否生效
    /**
     * @param {*} type 决定跳转的节点类型 3:合同已生效协议未签订
     */
    doneDetailDataAfter(savedData,step){
        let { pkOrg, appCode} = this.props;
        let { agFlag } = this.state;
        ajax({
            url: '/nccloud/hrcm/make/MakeAddSaveActionAfter.do',
            data: {
                step: step,
                appCode: appCode,
                pk_org: pkOrg,
                modename: 'hi_psndoc_ctrt',         //暂时写死
                isSelected: agFlag,                 //确认生效弹窗中间的单选框是否选中(但后台没处理)，true/false
                savedData: savedData                //上个接口返回的数据
            },
            success: res => {
                if(res.success && res.data){
                    let data = res.data;
                    let msg = data.msg;
                    let step = data.step;
                    //step 传 4 点击确定生效
                    //step 传 5 点击取消
                    if(step == '4'){  //是否生效
                        let fn = {
                            sureFn: () => this.isTakeEffectEvent(savedData,step),
                            cancelFn : () => this.handdleCancelFn(savedData)
                        }
                        this.promptBoxModal(this.setCheckbox(msg),fn,step);
                    }else if(step == '99'){ //是否选中协议类型
                        let jobpks = data.jobpks;
                        let savedData = data.savedData;
                        // if(agFlag){ //判断是否勾选协议
                            // cacheTools.set('isSignEffect', true);
                            // this.setState({
                            //     isSignEffect : true
                            // },()=>{
                                // let isSignEffect = cacheTools.get('isSignEffect');
                                // this.props.closeFormCardModal && this.props.closeFormCardModal({data:savedData,jobpks: jobpks,flag: agFlag, isSignEffect: isSignEffect});
                            // })
                        // }
                        if(data.isEffect === 'Y'){
                            cacheTools.set('isSignEffect', true);
                            if(agFlag){
                                this.props.closeFormCardModal && this.props.closeFormCardModal({data:savedData,jobpks: jobpks,flag: agFlag, isSignEffect: true});
                            }else{
                                this.props.closeFormCardModal && this.props.closeFormCardModal({data:savedData,jobpks: jobpks,flag: agFlag, isSignEffect: true, type: '3'});
                            }
                        }else{
                            cacheTools.set('isSignEffect', false);
                            this.props.closeFormCardModal && this.props.closeFormCardModal({data:savedData,jobpks: jobpks,flag: agFlag, isSignEffect: false});
                        }
                    }else{
                        this.props.closeFormCardModal && this.props.closeFormCardModal();
                    }
                }else{
                    this.props.closeFormCardModal && this.props.closeFormCardModal();
                }
            }
        })
    }
    
    //合同操作取消时动作
    handdleCancelFn(data){
        let { agFlag } = this.state;
        cacheTools.set('isSignEffect', false);
        cacheTools.set('pkPsndocSubs', data);
        if(agFlag){
            this.doneDetailDataAfter(data,'5');
        }else{
            this.props.closeFormCardModal && this.props.closeFormCardModal({data : data});
        }
    }

    //设置页面FormCar Id
    setFormCardId(id,flag,data){
        this.props.setRollBackFlag(flag);
        this.setState({
            dataCard_add: ''
        },()=>{
            this.setState({
                dataCard_add: id,
            },()=>{
                this.props.form.setAllFormValue({[id]: data});
                this.props.form.setFormStatus(id,'edit');
                if(data && data.rows[0].values.ifprop.value === true || data.rows[0].values.ifprop.value === 'Y'){
                    this.props.form.setFormItemsValue(id,{'ifprop':{display: null, value: true, scale: "-1"}})
                    this.props.form.setFormItemsDisabled(id, {promonth: false, prop_unit: false, probegindate: false, probenddate: false})
                }else{
                    this.props.form.setFormItemsValue(id,{'ifprop':{display: null, value: false, scale: "-1"}})
                    this.props.form.setFormItemsDisabled(id, {promonth: true, prop_unit: true, probegindate: true, probenddate: true})
                }
            })
        })
    }

    handleEditFormData(props,moduleId,key,value,oldValue,f,g,h){
        let { appCode } = this.props;
        let { dataCard_add } = this.state;
        chectFormAction(key, moduleId, props, [dataCard_add], appCode);
    }

    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'pk_conttext'){
            let pk_org = this.state.pk_org;
            let agreementType = !!data.agreementtype ? data.agreementtype.value : '';
            let obj = {
                "pk_org": pk_org,
                "agreementType": agreementType,
                "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
            }
            this.setQueryCondition(moduleId, key, obj);
        }else if(key  === 'pk_post'){
            let pk_dept = data['pk_psnjob.pk_dept.pk_dept'] && data['pk_psnjob.pk_dept.pk_dept'].value;
            let obj = {
                "pk_dept": pk_dept
            }
            this.setQueryCondition(moduleId, key, obj);
        }
        return true;
    }

    // 编辑前事件操作增加queryCondition条件
    setQueryCondition(moduleId, key, param){
        let meta = this.props.meta.getMeta();
        if(!!meta[moduleId].items.find(item => item.attrcode === key)){
            meta[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }else{
            meta['traincontAgreeInfo_add'].items.find(item => item.attrcode === key).queryCondition = function () {
                return param
            };
        }
        this.props.meta.setMeta(meta);
    }

    //获取formCard Id
    getFormCardId(){
        let formCardId = this.state.dataCard_add;
        return formCardId;
    }

    //确认弹窗
    promptBoxModal(context,fn = {},args){ //context 内容；fn 执行的方法；args 传递的参数
        let { sureFn, cancelFn } = fn;
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.json['hrcm-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: this.state.json['hrcm-000034'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: this.state.json['hrcm-000035'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn:true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick:  ()=> { sureFn && sureFn(args) } ,   // 确定按钮点击调用函数,非必输
            cancelBtnClick:  ()=>{ cancelFn && cancelFn(args) },  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop:false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }

    //checkbox复选框
    setCheckbox(msg){
        return (
            <div className="done-pop">
                <div className="is-sure">{msg}</div>
                <NCCheckbox
                    onChange={this.changeCheck}
                >{this.state.json['hrcm-000010']}</NCCheckbox>
            </div>
        )
    }

    //checkbox复选框改变值
    changeCheck(v){
        this.setState({
            agFlag : v
        })
    }

    render(){
        let { form, appCode } = this.props;
        let { createForm } = form;
        let { dataCard_add, expandArr } = this.state;
        return (
            dataCard_add ? 
            createForm(dataCard_add, {
                useFixedHeader: true,
                onAfterEvent: this.handleEditFormData.bind(this),
                onBeforeEvent: this.handleEditBefore.bind(this),
                expandArr: expandArr, // 设置关联表单某个区域展开
            }) : ''
        )
    }
}

export default FormCard;